package aeolus.wind.spider.biz.service.impl;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import sun.misc.BASE64Encoder;
import aeolus.wind.spider.biz.constants.Constants;
import aeolus.wind.spider.biz.constants.LoginItem;
import aeolus.wind.spider.biz.dao.BDBStore;
import aeolus.wind.spider.biz.dataobject.Identity;
import aeolus.wind.spider.biz.service.interfaces.IdentityService;

import com.sleepycat.je.Transaction;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityIndex;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;

public class IdentityServiceImpl implements IdentityService {

    private static EntityStore                              identityStore;
    private static PrimaryIndex<String, Identity>           identityNameIndex;
    private static SecondaryIndex<String, String, Identity> leaderNameIndex;

    static {
        BDBStore bdbStore = new BDBStore(Constants.IDENTITY_BIZ_NAME);
        identityStore = bdbStore.createEntityStore(Constants.IDENTITY_BIZ_NAME);
        identityNameIndex = identityStore.getPrimaryIndex(String.class, Identity.class);
        leaderNameIndex = identityStore.getSecondaryIndex(identityNameIndex, String.class, "leaderName");
    }

    /**
     * 实例化时调用
     */
    public IdentityServiceImpl() {
        Identity rootIdentity = findIdentity(Constants.ROOT);
        if (rootIdentity == null) {
            Identity identity = new Identity();
            identity.setName(Constants.ROOT);
            identity.setPasswd(Constants.ROOT);
            identity.setLeaderName(Constants.ROOT_LEADER);
            identity.setAbleToLeadGroup(true);
            saveIdentity(identity);
        }
    }

    @Override
    public List<Identity> listIdentitiesLeaded(String identityName) {
        List<Identity> list = new ArrayList<Identity>();
        Identity id = null;
        EntityIndex<String, Identity> index = getLeaderNameIndex().subIndex(identityName);
        EntityCursor<Identity> ec = index.entities();
        while ((id = ec.next()) != null)
            list.add(id);
        ec.close();
        Identity mySelf = findIdentity(identityName);
        list.add(mySelf);
        return list;
    }

    @Override
    public void saveIdentity(Identity identity) {
        Transaction txn = getStore().getEnvironment().beginTransaction(null, null);
        identity.setPasswd(encoderByMd5(identity.getPasswd()));
        getPi().put(txn, identity);
        txn.commit();
    }

    @Override
    public void deleteIdentity(String identityName) {
        Transaction txn = getStore().getEnvironment().beginTransaction(null, null);
        getPi().delete(txn, identityName);
        txn.commit();
    }

    @Override
    public Identity findIdentity(String identityName) {
        if (StringUtils.isBlank(identityName)) return null;
        return getPi().get(identityName);
    }

    private Identity findIdentity(String identityName, String passwd) {
        if (StringUtils.isBlank(identityName) || StringUtils.isBlank(passwd)) return null;
        Identity identity = getPi().get(identityName);
        if (identity != null) {
            if (encoderByMd5(passwd).equals(identity.getPasswd())) return identity;
        }
        return null;
    }

    @Override
    public LoginItem findLoginItem(String identityName, String passwd) {
        Identity identity = findIdentity(identityName, passwd);
        LoginItem loginItem = null;
        if (identity != null) {
            loginItem = new LoginItem(identity);
            Identity leaderIdentity = findIdentity(identity.getLeaderName());
            loginItem.setLeaderGroupName(leaderIdentity.getGroupName());
            loginItem.setRoot(identityName.equals(Constants.ROOT));
        }
        return loginItem;
    }

    public String encoderByMd5(String str) {
        // 确定计算方法
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            // 加密后的字符串
            String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
            return newstr;
        } catch (Exception e) {
            e.printStackTrace();
            return str;
        }
    }

    private EntityStore getStore() {
        return identityStore;
    }

    private PrimaryIndex<String, Identity> getPi() {
        return identityNameIndex;
    }

    private SecondaryIndex<String, String, Identity> getLeaderNameIndex() {
        return leaderNameIndex;
    }

    // public static void main(String args[]) {
    // IdentityService is = new IdentityServiceImpl();
    // Identity identity = new Identity();
    // identity.setName("袁岳峰");
    // identity.setPasswd("123456");
    // is.saveIdentity(Constants.ROOT_GROUP, identity);
    // List<Identity> list = is.listIdentities(Constants.ROOT_GROUP);
    // for (Identity id : list) {
    // System.out.println("姓名: " + id.getName());
    // System.out.println("密码: " + id.getPasswd());
    // }
    // is.deleteIdentity(Constants.ROOT_GROUP, "袁岳峰");
    //
    // list = is.listIdentities(Constants.ROOT_GROUP);
    // for (Identity id : list) {
    // System.out.println("姓名: " + id.getName());
    // System.out.println("密码: " + id.getPasswd());
    // }
    // }

}
